<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi;
use Wechat\WechatAuth;
/**
 * 后台用户控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class UserController extends CommonController {

    protected $tableName = null;   // 当前数据模型对应表面

    /**
     * 用户管理首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function index(){
        $nickname       =   I('nickname');
        $map['status']  =   array('egt',0);
        //$count = $model->where($map)->count();
        if(is_numeric($nickname)){
            $map['uid|nickname']=   array(intval($nickname),array('like','%'.$nickname.'%'),'_multi'=>true);
        }else{
            $map['nickname']    =   array('like', '%'.(string)$nickname.'%');
        }

        $list   = $this->lists('Member', $map);
        $prefix   = C('DB_PREFIX');

        foreach($list as $key=>$val)
        {
            $map1['oga.uid'] = $val['uid'];
            $group = M()
                ->table($prefix.'auth_group_access oga')
                ->join ($prefix."auth_group ag on ag.id=oga.group_id")
                ->where($map1)
                ->find();
            $map2['id'] = $val['uid'];
            $user = M('UcenterMember')
                    ->where($map2)
                    ->find();
            $list[$key]['mobile'] = $user['mobile'];
            $list[$key]['email'] = $user['email'];
            $list[$key]['role_name'] = $group['title'];
            $list[$key]['group_id'] = $group['id'];

            $where['id'] = $val['uid'];
            $result = M('ucenter_member')->where($where)->find();

            $list[$key]['level'] = $result['level'];
        }
//        int_to_string($list);




        $this->assign('_list', $list);
        $this->meta_title = '用户信息';
        $this->display();
    }

    /**
     * 分销列表首页
     * @author 麦当苗儿 <zuojiazi@vip.qq.com>
     */
    public function inviteList(){
        $map['status']  =   array('egt',0);
        $root = IS_ROOT ? 0 : UID;
        $list   = M('UcenterMember')->where($map)->select();
        $list   = D("Common/Tree")->toFormatTree($list, $title = 'username', $pk = 'id', $pid = 'pid', $root);
        $prefix   = C('DB_PREFIX');
        foreach($list as $key=>$val)
        {
            $map1['oga.uid'] = $val['id'];
            $group = M()
                ->table($prefix.'auth_group_access oga')
                ->join ($prefix."auth_group ag on ag.id=oga.group_id")
                ->where($map1)
                ->find();
            $member = M('Member')->where(array('uid'=>$val['id']))->find();
            $business = M('Business')->where(array('id'=>$member['business_id']))->find();
            $list[$key]['nickname'] = $val['username'];
            $list[$key]['alias'] = $member['alias'];
            $list[$key]['business_name'] = $business['name'];
            $list[$key]['role_name'] = $group['title'];
            $list[$key]['group_id'] = $group['id'];
        }

        $this->assign('_list', $list);
        $this->display();
    }

    /**
     * 修改昵称初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updateNickname(){
        $nickname = M('Member')->getFieldByUid(UID, 'nickname');
        $map['id'] = UID;
        $user = M('UcenterMember')->where($map)->field('mobile,email')->find();
        $this->assign('nickname', $nickname);
        $this->assign('user', $user);
        $this->meta_title = '修改昵称';
        $this->display();
    }

    /**
     * 修改昵称提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitNickname(){
        //获取参数
        $nickname = I('post.nickname');
        $password = I('post.password');
        empty($nickname) && $this->error('请输入昵称');
        empty($password) && $this->error('请输入密码');

        //密码验证
        $User   =   new UserApi();
        $uid    =   $User->login(UID, $password, 4);
        ($uid == -2) && $this->error('密码不正确');

        $Member =   D('Member');

        $map['uid'] = array('neq', UID);
        $map['nickname'] = array('eq', $nickname);
        $validate= $Member->where($map)->find();
        if($validate)
        {
            $this->error('输入的昵称已经被占用！');
        }
        $data['nickname'] = $nickname;
        $res = $Member->where(array('uid'=>$uid))->save($data);

        if(false !== $res){
            $user               =   session('user_auth');
            $user['username']   =   $data['nickname'];
            session('user_auth', $user);
            session('user_auth_sign', data_auth_sign($user));
            $map2['id'] = array('neq', UID);
            $map2['mobile'] = array('eq', I('post.mobile'));
            $validate2= M('ucenter_member')->where($map2)->find();
            if($validate2)
            {
                $this->error('该手机号码被占用！');
            }

            $map3['id'] = array('neq', UID);
            $map3['email'] = array('eq', I('post.email'));
            $validate3= M('ucenter_member')->where($map3)->find();
            if($validate3)
            {
                $this->error('该邮箱号码被占用！');
            }

            $udata = M('ucenter_member')->where(array('uid'=>$uid))->find();
            $udata['mobile'] = I('post.mobile');
            $udata['email'] = I('post.email');
            M('ucenter_member')->save($udata);
            $this->success('成功修改个人资料！');
        }else{
            $this->error('修改失败！');
        }
    }

    /**
     * 修改密码初始化
     * @author huajie <banhuajie@163.com>
     */
    public function updatePassword(){
        $this->meta_title = '修改密码';
        $this->display('updatepassword');
    }

    /**
     * 修改密码提交
     * @author huajie <banhuajie@163.com>
     */
    public function submitPassword(){
        //获取参数
        $password   =   I('post.old');
        empty($password) && $this->error('请输入原密码');
        $data['password'] = I('post.password');
        empty($data['password']) && $this->error('请输入新密码');
        $repassword = I('post.repassword');
        empty($repassword) && $this->error('请输入确认密码');

        if($data['password'] !== $repassword){
            $this->error('您输入的新密码与确认密码不一致');
        }

        $Api    =   new UserApi();
        $res    =   $Api->updateInfo(UID, $password, $data);
        if($res['status']){
            $this->success('修改密码成功！');
        }else{
            if($res['info'] == -4)
            {
                $this->error('您输入的密码不符合要求！');
            }
            $this->error($res['info']);
        }
    }

    /**
     * 会员状态修改
     * @author 朱亚杰 <zhuyajie@topthink.net>
     */
    public function changeStatus($method=null){
        $id = array_unique((array)I('get.id',0));

        if( in_array(C('USER_ADMINISTRATOR'), $id)){
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',',$id) : $id;

        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] =   array('in',$id);
        $um['id'] = array('in',$id);
        switch ( strtolower($method) ){
            case 'forbiduser':
                $this->forbid('Member', $map );
                break;
            case 'resumeuser':
                $this->resume('Member', $map );
                break;
            case 'deleteuser':
                //$this->delete('Member', $map );
                D('Member')->where($map)->delete();
                D('UcenterMember')->where($um)->delete();
                $this->success('删除用户成功！');
                break;
            default:
                $this->error('参数非法');
        }
    }

    public function add($username = '', $password = '', $repassword = '', $email = '',$mobile='',$group_id=''){
        if(IS_POST){
            /* 检测密码 */
            if($password != $repassword){
                $this->error('密码和重复密码不一致！');
            }

            /* 调用注册接口注册用户 */
            $User   =   new UserApi;
            $uid    =   $User->register($username, $password, $email,$mobile);
            if(0 < $uid){ //注册成功
                $user = array('uid' => $uid, 'nickname' => $username, 'status' => 1);
                $user_role = array('uid' => $uid, 'group_id' => $group_id);
                if(!M('Member')->add($user)){
                    $this->error('用户添加失败！');
                } else {
                    M('auth_group_access')->add($user_role);
                    $this->success('用户添加成功！');
                }
            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        } else {
            $this->meta_title = '新增用户';
            $rules = M('AuthGroup')->field(true)->where(array('status'=>array('gt',0)))->select();
            $this->assign('rules',$rules);
            $this->display();
        }
    }
    public function editPassword()
    {
        if(IS_POST){
            $user = I('post.');
            empty($user['password']) && $this->error('请输入密码');
            if($user['password'] != $user['repassword'])
            {
                $this->error('两次输入的密码不一致');
            }
            $data['password'] = $user['password'];
            $Api    =   new UserApi();
            $res    =   $Api->eidtInfo($user['uid'], $data);
            if($res['status']){
                $this->success('成功修改用户密码！');
            }else
            {
                $this->error($res['info']);
            }

        }else
        {
            $prefix   = C('DB_PREFIX');
            $map['um.id'] = I('get.id');
            $info = M('UcenterMember')
                ->table($prefix.'ucenter_member um')
                ->join('left join '.$prefix.'auth_group_access aga on aga.uid = um.id')
                ->join('left join '.$prefix.'member m on m.uid = um.id')
                ->where($map)
                ->field('um.*,aga.group_id,m.nickname')
                ->find();
            $this->assign('info',$info);
            $rules = M('AuthGroup')->field(true)->select();
            $this->assign('rules',$rules);
            $this->display();
        }
    }

    /**
     * 编辑用户信息
     */
    public function editUserInfo(){
        $uid = I('get.id');

        if(IS_POST){
            $data = I();
            $result = M('Member')->where(array('uid'=>$uid))->save($data);
            FPC($result);

            if(is_numeric($result)){
                $this->success('更新成功!');
            }
            $this->error('更新失败!');
        }
        # 用户信息
        $info = M('Member')->where(array('uid'=>$uid))->find();
        # END-用户信息
        # 商家数据列表
        $businessList = M('Business')->where(array('status'=>1))->select();
        FPC($info);
        FPC($businessList);
        # END-商家数据列表
        $this->assign('info', $info);
        $this->assign('businessList', $businessList);
        $this->display();
    }


    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    private function showRegError($code = 0){
        switch ($code) {
            case -1:  $error = '用户名长度必须在16个字符以内！'; break;
            case -2:  $error = '用户名被禁止注册！'; break;
            case -3:  $error = '用户名被占用！'; break;
            case -4:  $error = '密码长度必须在6-30个字符之间！'; break;
            case -5:  $error = '邮箱格式不正确！'; break;
            case -6:  $error = '邮箱长度必须在1-32个字符之间！'; break;
            case -7:  $error = '邮箱被禁止注册！'; break;
            case -8:  $error = '邮箱被占用！'; break;
            case -9:  $error = '手机格式不正确！'; break;
            case -10: $error = '手机被禁止注册！'; break;
            case -11: $error = '手机号被占用！'; break;
            default:  $error = '未知错误';
        }
        return $error;
    }

    /**
     * 批量删除
     */
    public  function batchDel()
    {
        $id = array_unique((array)I('get.delids',0));

        if( in_array(C('USER_ADMINISTRATOR'), $id)){
            $this->error("不允许对超级管理员执行该操作!");
        }
        $id = is_array($id) ? implode(',',$id) : $id;
        if ( empty($id) ) {
            $this->error('请选择要操作的数据!');
        }
        $map['uid'] =   array('in',$id);
        $this->delete('Member', $map );
    }


    /**
     * 行为日志列表
     * @author huajie <banhuajie@163.com>
     */
    public function actionLog()
    {
        FPC($_SERVER);
        //获取列表数据
//        $map = $this->_search();
        $map['al.status'] = array('gt', -1);
        $map['al.user_id'] = I('id');
        $map['al.action_id'] = M('Action')->where(array('name'=>array('in', 'read_category')))->getField('id');
        $prefix = C('DB_PREFIX');
        $model = M()
            ->table($prefix . 'action_log al')
//            ->join($prefix . 'member m ON al.user_id=m.uid', 'LEFT')
//            ->join($prefix . 'document d ON d.id=al.record_id', 'LEFT');
            ->join($prefix . 'category c ON c.id=al.record_id', 'LEFT');
        $list = $this->lists($model, $map, 'al.id desc', 'al.*, c.title');
//        int_to_string($list);
        FPC();
        FPC($list);
        $this->assign('_list', $list);
        $this->display();
    }

    /**
     * 微信消息推送
     */
    public function wechatPush(){
//        FPC(I());
//        S('WECHATADDONS_CONF', null);
        $this->wechatConfig = S('WECHATADDONS_CONF');
        FPC($this->wechatConfig);
        if(empty($wechatConfig)){
            S('WECHATADDONS_CONF',get_addon_config('Wechat'),0);
            $this->wechatConfig = S('WECHATADDONS_CONF');
        }
        (session('push_user_id') && $uid = session('push_user_id')) || $this->error('用户id不能为空!');
        (I('get.article_id') && $articleId = I('get.article_id')) || $this->error('推荐文章id不能为空!');
        try {
//            $this->wechat = new Wechat($token);
            $this->wechatAuth = new WechatAuth($this->wechatConfig['appid'], $this->wechatConfig['appsecret']);
            $openid = M('MemberAuth')->where(array('uid'=>$uid))->getField('auth_code');
//            $content = M('Document')->where(array('id'=>$articleId))->getField('title'); // 文档描述
            $documentArr = M('Document')->field('id, title, description, cover_id')->where(array('id'=>$articleId))->find(); // 文档描述

            FPC($documentArr);

            $tokenArr = $this->wechatAuth->getAccessToken();    // 获取access_token

            if($openid && $documentArr){
//                $result = $this->wechatAuth->messageCustomSend($openid, $content);
                /**
                 * 发送一条图文消息
                 * @param  string $openid      用户的openid
                 * @param  string $title       文章标题
                 * @param  string $discription 文章简介
                 * @param  string $url         文章连接
                 * @param  string $picurl      文章缩略图
                 */
                $picurl = M('picture')->where(array('id'=>$documentArr['cover_id']))->getField('path');
                FPC($picurl);
                $picurl = $picurl ? urlAddDomain($picurl) : '';

                $url = str_replace('admin.php', 'index.php', U('Article/detail', array('id'=>$documentArr['id']), true, true, false));
                $result = $this->wechatAuth->sendNewsOnce($openid, $documentArr['title'], $documentArr['description'], $url, $picurl);
            }

            if($result['errcode']>0){
                $this->error($this->getWechatError($result['errcode']));
            }else{
//                session('push_user_id', null);
                $this->success('推送成功!');
            }

        } catch (\Exception $e) {
            logs('微信认证对象实例化异常!'.$e->getMessage());
            $this->error('微信认证对象实例化异常!'.$e->getMessage());
        }
        $this->error('推送失败!');
    }


    /**
     * 导出表格文件
     */
    public function outxls()
    {
        session_write_close();      // 此函数会释放session数据的排它锁
        S('excelCount', 0);
        S('excelNumber', 0);
        S('excelStatus', 0);    // 导出状态, 默认未完成  -1没有数据,0未完成, 1已完成
        $where  =   array('um.status'=>array('egt',0));
        $where['al.action_id'] = M('Action')->where(array('name'=>array('in', 'read_category,read_article')))->getField('id', true);
        $where['al.action_id'] && $where['al.action_id'] = array('in', implode($where['al.action_id'], ','));
        if(empty($where['al.action_id']))
            unset($where['al.action_id']);
        $prefix   = C('DB_PREFIX');
        $export_model = M()
                        ->table($prefix.'ucenter_member um')
                        ->join($prefix.'member m ON m.uid=um.id', 'LEFT')
                        ->join($prefix.'action_log al ON al.user_id=um.id', 'LEFT');
        C('LIST_ROWS', -1);    // 不分页配置
//        echo "<pre>";
        $result = $this->lists($export_model, $where, 'um.id desc,al.create_time desc', 'um.*, m.nickname,al.*', null, true);
        S('excelCount', $result['total']);
        $root = IS_ROOT ? 0 : UID;
        $list = D("Common/Tree")->toTree($list=$result['list'], $pk='id',$pid = 'pid',$child = '_child', $root);
        foreach($list as &$arr){
            if($arr['record_id'] && $arr['model']){
                $arr['modelName'] = $arr['model']=='article' ? 'document' : $arr['model'];
                $arr['title'] = M($arr['modelName'])->where(array('id'=>$arr['record_id']))->getField('title');
            }else{
                unset($arr);
            }
        }
        unset($arr);
        $outorder = array();
        foreach($list as $key=>$val)
        {
            S('excelNumber', $key+1);
            $outorder[$key]['no'] = $key+1;
            $outorder[$key]['nickname'] = $val['nickname'];
            $outorder[$key]['mobile'] = $val['mobile'];
            $outorder[$key]['crate_time'] = date('Y-md H:i:s', $val['create_time']);
            $outorder[$key]['remark'] = $val['remark'];
            $outorder[$key]['title'] = $val['title'];
        }
        $headArr=array('序号','用户名', '手机', '操作时间', '行为', '阅读标题');

        $filename='用户阅读记录';
        $this->xlsout($filename,$headArr,$outorder);
    }
}